package com.chap17;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * <p>
 * <code>CompletionServiceDemo</code>
 * </p>
 *
 * @author junbao3
 * TODO
 * @date 2023-05-06 10:09
 * Copyright (C) 2021 IFlyTek. All rights reserved.
 */
@Slf4j
public class CompletionServiceDemo {
    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        CompletionService<Integer> cs = new ExecutorCompletionService<>(executorService);

        cs.submit(()->getPriceByS1());
        cs.submit(()->getPriceByS2());
        cs.submit(()->getPriceByS3());

        for (int i = 0; i < 3; i++) {
            //从阻塞队列获取FutureTask  cs.take()
            Integer r = cs.take().get();
            executorService.execute(()->save(r));
        }
        executorService.shutdown();
    }

    private static void save(Integer r){
      log.debug("保存询价结果：{}",r);
    }

    private static Integer getPriceByS1() throws InterruptedException {
        TimeUnit.MILLISECONDS.sleep(5000);
        log.debug("电商S1询价信息是1200");
        return 1200;
    }

    private static Integer getPriceByS2() throws InterruptedException {
        TimeUnit.MILLISECONDS.sleep(8000);
        log.debug("电商S2询价信息是1000");
        return 1000;
    }

    private static Integer getPriceByS3() throws InterruptedException {
        TimeUnit.MILLISECONDS.sleep(3000);
        log.debug("电商S3询价信息是800");
        return 800;
    }
}
